import { queryParkinglotNames } from '@/pages/Parking/Spot/service';
import { queryCompanies } from '@/pages/SystemUser/service';
import { Auths, Role } from '@/utils/types.d';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Tooltip } from 'antd';
import { useModel, history } from 'umi';
import { mapVehicleType } from '../utils';
import CancelRecord from './components/CancelRecord';
import CreateMemberRecord from './components/CreateMemberRecord';
import RenewalType from './components/RenewalType';
import { queryMemberCardNames, queryMemberRecords } from './service';
import { MemberRecordStatus } from './types.d';
import type { MemberRecordTableItem } from './types.d';
import { useRef, useState } from 'react';
export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.member || []) : new Set();
  const ifCreate = auths.has(Auths.CREATE);
  const ifModify = auths.has(Auths.MODIFY);
  const actionRef = useRef<ActionType>();
  const [currRecord, setCurrRecord] = useState<MemberRecordTableItem | null>(null);
  const [renewalVisible, setRenewalVisible] = useState<boolean>(false);
  const columns: ProColumns<MemberRecordTableItem>[] = [
    {
      title: '用户昵称',
      dataIndex: 'memberName',
      hideInSearch: true,
      align: 'center',
      hideInForm: true,
    },
    {
      title: '会员卡号',
      dataIndex: 'recordNo',
      // hideInTable: true,
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '会员卡名',
      dataIndex: 'cardNo',
      align: 'center',
      hideInForm: true,
      fieldProps: {
        showSearch: true,
      },
      render: (_, record) => record.cardName,
      debounceTime: 300,
      request: (val) => queryMemberCardNames(val.keyWords),
    },
    {
      title: '适用车型',
      dataIndex: 'vehicleType',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (_, record) =>
        record?.vehicleType?.map((item) => mapVehicleType(item)).join(';') || '-',
    },
    {
      title: '所属用户',
      dataIndex: 'ownerId',
      align: 'center',
      hideInForm: true,
      hideInTable: currUser?.role !== Role.ADMIN,
      hideInSearch: currUser?.role !== Role.ADMIN,
      fieldProps: { showSearch: true },
      render: (_, record) => record?.ownerInfo?.ownerName,
      debounceTime: 300,
      request: (val) => queryCompanies(val.keyWords),
    },
    {
      title: '用户手机号',
      dataIndex: 'phone',
      align: 'center',
      hideInForm: true,
    },
    {
      title: '用户车牌号',
      dataIndex: 'plateNumber',
      align: 'center',
      hideInForm: true,
    },
    {
      title: '路段名称',
      align: 'center',
      dataIndex: 'parkingLots',
      hideInForm: true,
      fieldProps: { showSearch: true },
      render: (_, record) => {
        let tempText = '-';
        if (record.allParkValid) {
          tempText = '全路段通用';
        } else {
          tempText =
            record?.parkingLots?.map((item) => item.parkingLotName).join('; ') ||
            record.parkingLotName;
        }
        return (
          <Tooltip title={tempText}>
            <div
              style={{
                maxWidth: '300px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                margin: '0 auto',
              }}
            >
              {tempText}
            </div>
          </Tooltip>
        );
      },
      debounceTime: 300,
      request: (val) => queryParkinglotNames(val.keyWords),
    },
    // {
    //   title: '价格',
    //   align: 'center',
    //   dataIndex: 'price',
    //   hideInForm: true,
    //   hideInSearch: true,
    //   valueType: 'money',
    // },
    // {
    //   title: '卡类型',
    //   align: 'center',
    //   dataIndex: 'cardType',
    //   hideInForm: true,
    //   valueEnum: {
    //     year: '年卡',
    //     season: '季卡',
    //     month: '会员卡',
    //   },
    // },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      hideInForm: true,
      valueEnum: {
        1: { text: '正常', status: 'success' },
        2: { text: '过期', status: 'error' },
        3: { text: '作废', status: 'default' },
      },
    },
    {
      title: '起始时间',
      align: 'center',
      dataIndex: 'startTime',
      hideInForm: true,
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: '结束时间',
      align: 'center',
      dataIndex: 'endTime',
      hideInForm: true,
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
      hideInForm: true,
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      fixed: 'right',
      render: (_, record, x, action) => [
        ifModify && record.status != MemberRecordStatus.cancel && (
          <a
            onClick={() => {
              setCurrRecord(record);
              setRenewalVisible(true);
            }}
          >
            续费
          </a>
        ),
        ifModify && record?.status == MemberRecordStatus.normal && (
          <CancelRecord recordId={record._id} reload={() => action?.reload()} />
        ),
        <a
          key={record.recordNo}
          onClick={() => {
            history.push({
              pathname: '/member/renewals',
              state: record.recordNo,
            });
          }}
        >
          查看购买记录
        </a>,
      ],
    },
  ];
  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: '会员卡',
        breadcrumb: {
          routes: [
            { path: '/', breadcrumbName: '首页' },
            { path: '/member', breadcrumbName: '会员卡管理' },
            { path: '/member/record', breadcrumbName: '会员卡' },
          ],
        },
      }}
    >
      <ProTable<MemberRecordTableItem>
        columns={columns}
        rowKey="recordNo"
        scroll={{ x: true }}
        search={{
          labelWidth: 'auto',
        }}
        actionRef={actionRef}
        style={{ whiteSpace: 'nowrap' }}
        dateFormatter="string"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryMemberRecords(param, sort);
          return res;
        }}
        toolBarRender={(action) => [
          ifCreate && <CreateMemberRecord reload={() => action?.reload()} />,
        ]}
      />
      {renewalVisible && currRecord && (
        <RenewalType
          visible={renewalVisible}
          close={() => {
            setRenewalVisible(false);
            setCurrRecord(null);
          }}
          currRecord={currRecord}
          reload={() => actionRef?.current?.reload()}
        />
      )}
    </PageHeaderWrapper>
  );
};
